/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fortasoft.hatfield.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CertificateVerificationControl {

    static Logger log = LoggerFactory
            .getLogger(CertificateVerificationControl.class);

    public static final String BEAN_NAME = "certificateVerificationControl";

    public static void disableCertVerification() {

        log.warn("* * * SSL Certificate Verification is disabled * * *");
        try {

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            // Create empty HostnameVerifier

            sc.init(null, createTrustAllCertsX509TrustManagerArray(),
                    new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection
                    .setDefaultHostnameVerifier(createVeryifyAllHostnameVerifier());
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean verificationDisabled = false;

    public boolean isVerificationDisabled() {
        return verificationDisabled;
    }

    public void setVerificationDisabled(boolean b) {
        this.verificationDisabled = b;
        if (verificationDisabled == true) {
            try {
                disableCertVerification();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    public static HostnameVerifier createVeryifyAllHostnameVerifier() {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        return hv;
    }

    public static TrustManager[] createTrustAllCertsX509TrustManagerArray() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] certs,
                    String authType) {
                // Trust always
            }

            public void checkServerTrusted(X509Certificate[] certs,
                    String authType) {
                // Trust always
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } };
        return trustAllCerts;
    }
}
